#!/usr/bin/env python
#coding=utf-8

import time, os, json, re
from decimal import Decimal
from flask import Blueprint, request, session, redirect, current_app, abort, url_for, g, render_template, make_response
from flask.ext.sqlalchemy import Pagination
import sqlalchemy
import sqlalchemy.orm
import sqlalchemy.ext.declarative

from codingabc.helpers import log_debug, toint, get_count, log_info
from codingabc.database import db
from codingabc.response import ResponseJson

from app.services.myqiniu import QiniuUploadService
from app.models.menu import Menu
from app.models.user import User
from app.models.sys import SysMessage
from app.helpers.common import model_to_dict, kt_to_dict, menu

sys = Blueprint('sys', __name__)
resjson = ResponseJson()
resjson.module_code = 11

@sys.route('/menu_list')
@sys.route('/menu_list/<int:page>')
@sys.route('/menu_list/<int:page>-<int:page_size>')
def menu_list(page=1, page_size=20):
    """菜单列表"""
    g.page_type = 'search'
    g.title = u'菜单列表'
    g.add_new = True
    g.button_name = u'新增菜单'

    args = request.args
    endpoint = args.get('endpoint', '')
    endpoint_name = args.get('endpoint_name', '')
    menu_type = toint(args.get('menu_type', '-1'))

    q = Menu.query
    if endpoint:
        q = q.filter(Menu.endpoint.like(u'%'+endpoint+u'%'))

    if endpoint_name:
        q = q.filter(Menu.endpoint_name.like(u'%'+endpoint_name+u'%'))

    if menu_type == 0:
        q = q.filter(Menu.parent_id == 0)

    if menu_type > 0:
        q = q.filter(Menu.parent_id > 0)

    menu_count = get_count(q)
    menu_list  = q.order_by(Menu.menu_id.desc()).\
                offset((page-1)*page_size).limit(page_size).all()

    pagination  = Pagination(None, page, page_size, menu_count, None)
    session['menu'] = menu(session.get('role_id'))
    res = make_response(render_template('sys/menu_list.html.j2', menu_list=menu_list, pagination=pagination))
    res.set_cookie('goback_url', request.url)
    return res


@sys.route('/menu_add', methods=['GET', 'POST'])
def menu_add():
    """新增菜单"""
    g.title = u'新增菜单'
    g.page_type = ''

    main_menu_list = Menu.query.filter(Menu.parent_id == 0).\
                    order_by(Menu.menu_id.asc()).all()

    return render_template('sys/menu_add.html.j2', f={}, main_menu_list=main_menu_list)


@sys.route('/menu_edit')
def menu_edit():
    """菜单编辑"""
    g.title = u'菜单编辑'
    g.page_type = ''

    menu_id = toint(request.args.get('menu_id', '0'))
    if menu_id <= 0:
        return u'参数出错'

    p = Menu.query.get_or_404(menu_id)
    menu_type = 0 if p.parent_id == 0 else 1
    setattr(p,'menu_type',menu_type)
    main_menu_list = Menu.query.filter(Menu.parent_id == 0).\
                    order_by(Menu.menu_id.asc()).all()

    return render_template('sys/menu_add.html.j2', f=p, main_menu_list=main_menu_list)


@sys.route('/menu_save')
def menu_save():
    """保存菜单"""
    g.title = u'保存菜单'
    g.page_type = ''

    args = request.args
    menu_id     = toint(args.get('menu_id', '0'))
    endpoint          = args.get('endpoint', '').strip()
    endpoint_name     = args.get('endpoint_name', '').strip()
    endpoint_icon     = args.get('endpoint_icon', '').strip()
    menu_type         = toint(args.get('menu_type', '0'))
    sort_order        = toint(args.get('sort_order', '0'))
    main_menu_id      = toint(args.get('main_menu_id', '0'))

    if menu_id <= 0:
        menu_info = Menu.create()
        # 判断新增端点是否已经存在
        if menu_type == 0:
            e_q = Menu.query.filter(Menu.endpoint == endpoint).filter(Menu.parent_id == 0)
        else:
            e_q = Menu.query.filter(Menu.endpoint == endpoint).filter(Menu.parent_id > 0)
        e = e_q.first()
        if e:
            return u'新增端点:%s已经存在'% endpoint

        # 判断新增端点名称是否存在
        en = e_q.filter(Menu.endpoint_name == endpoint_name).first()
        if en:
            return u'新增端点名称:%s已经存在'% endpoint_name
    else:
        menu_info = Menu.get(menu_id)

    if menu_type == 1 and main_menu_id <= 0:
        return u'主菜单参数出错'

    parent_id = main_menu_id if menu_type == 1 else 0

    menu_info.update(parent_id=parent_id,
                            endpoint=endpoint,
                            endpoint_name=endpoint_name,
                            endpoint_icon=endpoint_icon,
                            sort_order=sort_order,
                            commit=True)

    session['menu'] = menu(session.get('role_id'))
    return u'ok'


@sys.route('/delete_menu')
def delete_menu():
    """移除菜单"""

    menu_id = toint(request.args.get('menu_id', '0'))

    if menu_id <= 0:
        return u'参数出错'

    m = Menu.query.get(menu_id)

    if not m:
        return u'此菜单已经移除'

    is_mparent = None
    if m.parent_id == 0:
        is_mparent = Menu.query.filter(Menu.parent_id == m.menu_id).first()

    if is_mparent:
        return u'此菜单存在子菜单,不能移除'

    m.delete(commit=True)

    return u'ok'


@sys.route('/menu_sort/modify')
def menu_sort_modify():
    """修改菜单排序"""

    menu_id = toint(request.args.get('menu_id', '0'))
    new_sort = toint(request.args.get('new_sort', '0'))
    new_sort = new_sort if new_sort > 0 else -1

    if new_sort < 0:
        return u'只能输入大于0的数字'

    if new_sort > 10000000:
        return u'数字不能过大'

    if menu_id <= 0:
        return u'参数出错'

    m = Menu.get(menu_id)

    if m:
        m.sort_order = new_sort
        db.session.commit()

    return u'ok'

@sys.route('/menu_refresh')
def menu_refresh():
    """刷新菜单"""

    session['menu'] = menu(session.get('role_id'))

    return u'ok'


@sys.route('/ueditor/upload', methods=['GET', 'POST'])
def ueditor_upload():
    """ ueditor上传 """
    resjson.action_code = 10

    action = request.args.get('action')

    if action == 'config':
        # 解析JSON格式的配置文件
        # 这里使用PHP版本自带的config.json文件
        with open(os.path.join(current_app.static_folder, 'ue', 'php', 'config.json')) as fp:
            try:
                # 删除 `/**/` 之间的注释
                CONFIG = json.loads(re.sub(r'\/\*.*\*\/', '', fp.read()))
            except Exception as e:
                log_info('### error_msg:%s'% e)
                CONFIG = {}
            return json.dumps(CONFIG)

    # 获取上传文件
    upfile = request.files['upfile']

    # 上传 - 检查
    qus = QiniuUploadService(upfile)
    if not qus.check():
        return json.dumps({'state':'FAIL'})

    # 上传
    if not qus.upload():
        return json.dumps({'state':'FAIL'})

    return json.dumps({'state':'SUCCESS', 'source':qus.url, 'url':qus.url, 'title':qus.url, 'original':qus.url})
